<template>
	<view class="page-wrapper">
		<form @submit="submitForm" class="form-wrapper">
			<CommonInput type="text" v-model="registerForm.username" focus
				:placeholder="$t('pages.register.username_placeholder')" maxlength="20">
			</CommonInput>

            <view class="code-box row-gap">
                <CommonInput type="text" v-model="registerForm.yzm" class="input-wrapper"
                    :placeholder="$t('pages.register.code_placeholder')" maxlength="10">
                </CommonInput>
                <up-button type="primary" v-if="countdown" style="width: 7em;" plain disabled
					:text="countdown" class="middle-round button"></up-button>
			    <up-button type="primary" v-else style="width: 7em;"  class="middle-round button"
					:text="$t('pages.register.code_btn_text')" plain @click="getCode"></up-button>
            </view>		            

			<CommonInput class="row-gap" :type="showPasswdObj.passwd ? 'text' : 'password'"
				v-model="registerForm.password" :placeholder="$t('pages.register.password_placeholder')" maxlength="30">
				<template #suffix>
					<up-icon name="eye-off" v-if="showPasswdObj.passwd" size="24"
						@click="showPasswdObj.passwd=!showPasswdObj.passwd;"></up-icon>
					<up-icon name="eye" v-else size="24" @click="showPasswdObj.passwd=!showPasswdObj.passwd;"></up-icon>
				</template>
			</CommonInput>

			<CommonInput class="row-gap" :type="showPasswdObj.comfirmPasswd ? 'text' : 'password'"
				v-model="registerForm.repassword" :placeholder="$t('pages.register.confirm_pwd_placeholder')"
				maxlength="30">
				<template #suffix>
					<up-icon name="eye-off" v-if="showPasswdObj.comfirmPasswd" size="24"
						@click="showPasswdObj.comfirmPasswd=!showPasswdObj.comfirmPasswd;"></up-icon>
					<up-icon name="eye" v-else size="24"
						@click="showPasswdObj.comfirmPasswd=!showPasswdObj.comfirmPasswd;"></up-icon>
				</template>
			</CommonInput>

			<view style="margin-top: 20rpx;display: flex;align-items: flex-start;align-items: center;">
				<up-checkbox size="16" usedAlone v-model:checked="registerForm.checkedAgreement"
					style="display: inline-block;" activeColor="#15B8A6">
				</up-checkbox>
				<text class="common-text" style="width: 600rpx;word-break: break-all;">
					{{ $t('pages.register.agreementList.0') }} <text class="link-text"
						@click="toUserAgreement">{{ $t('pages.register.agreementList.1') }}</text>
				</text>
			</view>

			<view>
				<up-button form-type="submit" :text="$t('pages.register.register_btn')" size="normal" type="primary"
					style="width: 600rpx;margin-top:60rpx;" shape="circle"></up-button>
			</view>
		</form>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		reactive
	} from "vue";
	import {
		registerApi,
		getCodeApi
	} from "@/api/request";
	import {
		useI18n
	} from 'vue-i18n';
	import CommonInput from '@/components/CommonInput/index.vue';
	import {
		navigateToUniPage,
		CacheUtils,
	} from '@/utils/index.js';

	const { t } = useI18n();
	const countdown = ref(0); // 验证码倒计时
	const showPasswdObj = reactive({
		passwd: false,
		comfirmPasswd: false,
	});
	const registerForm = ref({
		checkedAgreement: false,
		username: '', // 账号（手机号/邮箱）
		yzm: '', // 验证码
		password: '', //  密码
		repassword: '', // 确认密码
		avatar: '', // 头像
	});

	const agreementPath = 'http://www.fepft.com/petcarehub_service_agreement.html';

	const toUserAgreement = () => navigateToUniPage(
		`/pages/webview/index?path=${ encodeURIComponent(agreementPath) }&&title=${ t('pages.login.concat_list.1') }`);


	const timer = ref(null);
	const getCode = async () => {
		if (countdown.value > 0) return;

		if (!validateUsername(registerForm.value.username)) {
			uni.showToast({
				title: t("pages.register.validate.username"),
				icon: "none"
			});
			return;
		}
		uni.showLoading({})
		let res = await getCodeApi({
			UserName: registerForm.value.username,
			isfindPw: 1
		});

		if (res.response.result == true) {
			uni.showToast({
				title: t("pages.register.validate.msg_success"),
				icon: 'none',
				duration: 1000
			});
			countdown.value = 59;
			timer.value = setInterval(() => {
				countdown.value -= 1;
				if (countdown.value <= 0) {
					clearInterval(timer.value);
					timer.value = null;
				}
			}, 1000);
		} else {
			uni.showToast({
				title: t("pages.register.validate.msg_error"),
				icon: 'none',
				duration: 1000
			});

			countdown.value = 60;
			clearInterval(timer.value);
			timer.value = null;
		}
	};

	const validateUsername = (username) => {
		const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		const phonePattern = /^[1][3-9][0-9]{9}$/;
		if (emailPattern.test(username) || phonePattern.test(username)) {
			return true
		} else {
			return false
		}
	};

	const validatePassword = (password) => {
		const passwordPattern = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,12}$/;
		return passwordPattern.test(password);
	};

	const isValidForm = computed(() => {
		return (
			validateUsername(registerForm.value.username) &&
			registerForm.value.yzm.length === 4 &&
			validatePassword(registerForm.value.password) &&
			registerForm.value.password === registerForm.value.repassword
		);
	});

	const submitForm = async () => {

		if (!registerForm.value.username || !registerForm.value.yzm || !registerForm.value.password || !
			registerForm.value.repassword) {
			uni.showToast({
				title: t("pages.register.validate.info_uncomplete"),
				icon: "none"
			});
			return;
		}
		if (!validateUsername(registerForm.value.username)) {
			uni.showToast({
				title: t("pages.register.validate.username"),
				icon: "none"
			});
			return;
		}
		if (!registerForm.value.yzm) {
			uni.showToast({
				title: t("pages.register.validate.msg_code"),
				icon: "none"
			});
			return;
		}
		if (!validatePassword(registerForm.value.password)) {
			uni.showToast({
				title: t("pages.register.validate.passwd_error"),
				icon: "none"
			});
			return;
		}
		if (registerForm.value.password !== registerForm.value.repassword) {
			uni.showToast({
				title: t("pages.register.validate.passwd_different"),
				icon: "none"
			});
			return;
		}
		if (!registerForm.value.checkedAgreement) {
			uni.showToast({
				title: t("pages.register.validate.un_check_agree"),
				icon: "none"
			});
			return;
		}
		let res = await registerApi(registerForm.value)

		if (res.response.result == true) {
			uni.showToast({
				title: t("common.operate_ok"),
				icon: 'success',
				duration: 1200
			})
			CacheUtils.set('userInfo', res.data);
			CacheUtils.set('userid', res.data.userid);
			navigateToUniPage('/pages/index/index')
		} else {
			uni.showToast({
				title: res.response.msg,
				icon: 'none',
				duration: 1200
			})
		}
	};
</script>


<style lang="scss" scoped>
	.form-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		row-gap: 40rpx;
		padding: 80rpx 10rpx;
	}

	.row-gap {
		margin: 40rpx auto 0;
	}

    .code-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
        column-gap: 12rpx;
        width: 620rpx;
        .input-wrapper{
            width: 400rpx;
            margin: 0;
        }        
        .button{
            margin: 0;
        }
    }
</style>